package myself.a009BinaryTree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 叶之越
 * Description
 * Date 2021/1/27
 * Time 18:50
 * Mail 739153436@qq.com
 */
public class IsCBT {
    // 是否是完全二叉树的非递归实现，采用层次遍历，对情况分类判断处理
    public static boolean isCBT1(Node head) {
        if (head == null) {
            return true;
        }

        Queue<Node> queue = new LinkedList<>();
        queue.add(head);
        boolean leaf = false;
        while (!queue.isEmpty()) {
            Node poll = queue.poll();

            System.out.println(poll.value);

            if (poll.right == null && poll.left != null) {
                return false;
            }
            if (leaf && (poll.right != null || poll.left != null)) {
                return false;
            }

            if (poll.left != null) {
                queue.add(poll.left);
            }

            if (poll.right != null) {
                queue.add(poll.right);
            }

            if (poll.right == null || poll.left == null) {
                leaf = true;
            }
        }

        return true;
    }

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }
}
